﻿/**  版本信息模板在安装目录下，可自行修改。
* sf_finance_settlement.cs
*
* 功 能： N/A
* 类 名： sf_finance_settlement
*
* Ver    变更日期             负责人  变更内容
* ───────────────────────────────────
* V0.01  2015-08-25 22:33:44   N/A    初版
*
* Copyright (c) 2012 SF Corporation. All rights reserved.
*┌──────────────────────────────────┐
*│　此技术信息为本公司机密信息，未经本公司书面同意禁止向第三方披露．　│
*│　版权所有：动软卓越（北京）科技有限公司　　　　　　　　　　　　　　│
*└──────────────────────────────────┘
*/
using System;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using SF.DBUtility;
using SF.Common;//Please add references
namespace SF.DAL
{
	/// <summary>
	/// 数据访问类:sf_finance_settlement
	/// </summary>
	public partial class sf_finance_settlement
	{
		public sf_finance_settlement()
		{}
		#region  BasicMethod

		/// <summary>
		/// 是否存在该记录
		/// </summary>
		public bool Exists(long id)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select count(1) from sf_finance_settlement");
			strSql.Append(" where id=@id");
			SqlParameter[] parameters = {
					new SqlParameter("@id", SqlDbType.BigInt)
			};
			parameters[0].Value = id;

			return DbHelperSQL.Exists(strSql.ToString(),parameters);
		}


		/// <summary>
		/// 增加一条数据
		/// </summary>
		public long Add(SF.Model.sf_finance_settlement model)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("insert into sf_finance_settlement(");
			strSql.Append("settlement_num,user_name,total_amount,received,not_received,state,create_time)");
			strSql.Append(" values (");
			strSql.Append("@settlement_num,@user_name,@total_amount,@received,@not_received,@state,@create_time)");
			strSql.Append(";select @@IDENTITY");
			SqlParameter[] parameters = {
					new SqlParameter("@settlement_num", SqlDbType.NVarChar,100),
					new SqlParameter("@user_name", SqlDbType.NVarChar,100),
					new SqlParameter("@total_amount", SqlDbType.Decimal,9),
					new SqlParameter("@received", SqlDbType.Decimal,9),
					new SqlParameter("@not_received", SqlDbType.Decimal,9),
					new SqlParameter("@state", SqlDbType.Int,4),
					new SqlParameter("@create_time", SqlDbType.DateTime)};
			parameters[0].Value = model.settlement_num;
			parameters[1].Value = model.user_name;
			parameters[2].Value = model.total_amount;
			parameters[3].Value = model.received;
			parameters[4].Value = model.not_received;
			parameters[5].Value = model.state;
			parameters[6].Value = model.create_time;

			object obj = DbHelperSQL.GetSingle(strSql.ToString(),parameters);
			if (obj == null)
			{
				return 0;
			}
			else
			{
				return Convert.ToInt64(obj);
			}
		}
		/// <summary>
		/// 更新一条数据
		/// </summary>
		public bool Update(SF.Model.sf_finance_settlement model)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("update sf_finance_settlement set ");
			strSql.Append("settlement_num=@settlement_num,");
			strSql.Append("user_name=@user_name,");
			strSql.Append("total_amount=@total_amount,");
			strSql.Append("received=@received,");
			strSql.Append("not_received=@not_received,");
			strSql.Append("state=@state,");
			strSql.Append("create_time=@create_time");
			strSql.Append(" where id=@id");
			SqlParameter[] parameters = {
					new SqlParameter("@settlement_num", SqlDbType.NVarChar,100),
					new SqlParameter("@user_name", SqlDbType.NVarChar,100),
					new SqlParameter("@total_amount", SqlDbType.Decimal,9),
					new SqlParameter("@received", SqlDbType.Decimal,9),
					new SqlParameter("@not_received", SqlDbType.Decimal,9),
					new SqlParameter("@state", SqlDbType.Int,4),
					new SqlParameter("@create_time", SqlDbType.DateTime),
					new SqlParameter("@id", SqlDbType.BigInt,8)};
			parameters[0].Value = model.settlement_num;
			parameters[1].Value = model.user_name;
			parameters[2].Value = model.total_amount;
			parameters[3].Value = model.received;
			parameters[4].Value = model.not_received;
			parameters[5].Value = model.state;
			parameters[6].Value = model.create_time;
			parameters[7].Value = model.id;

			int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		/// <summary>
		/// 删除一条数据
		/// </summary>
		public bool Delete(long id)
		{
			
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from sf_finance_settlement ");
			strSql.Append(" where id=@id");
			SqlParameter[] parameters = {
					new SqlParameter("@id", SqlDbType.BigInt)
			};
			parameters[0].Value = id;

			int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters);
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		/// <summary>
		/// 批量删除数据
		/// </summary>
		public bool DeleteList(string idlist )
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("delete from sf_finance_settlement ");
			strSql.Append(" where id in ("+idlist + ")  ");
			int rows=DbHelperSQL.ExecuteSql(strSql.ToString());
			if (rows > 0)
			{
				return true;
			}
			else
			{
				return false;
			}
		}

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public SF.Model.sf_finance_settlement GetModel(long id)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("select  top 1 id,settlement_num,user_name,total_amount,received,not_received,state,create_time from sf_finance_settlement ");
            strSql.Append(" where id=@id");
            SqlParameter[] parameters = {
					new SqlParameter("@id", SqlDbType.BigInt)
			};
            parameters[0].Value = id;

            SF.Model.sf_finance_settlement model = new SF.Model.sf_finance_settlement();
            DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return DataRowToModel(ds.Tables[0].Rows[0]);
            }
            else
            {
                return null;
            }
        }





		/// <summary>
		/// 得到一个对象实体
		/// </summary>
		public SF.Model.sf_finance_settlement DataRowToModel(DataRow row)
		{
			SF.Model.sf_finance_settlement model=new SF.Model.sf_finance_settlement();
			if (row != null)
			{
				if(row["id"]!=null && row["id"].ToString()!="")
				{
					model.id=long.Parse(row["id"].ToString());
				}
				if(row["settlement_num"]!=null)
				{
					model.settlement_num=row["settlement_num"].ToString();
				}
				if(row["user_name"]!=null)
				{
					model.user_name=row["user_name"].ToString();
				}
				if(row["total_amount"]!=null && row["total_amount"].ToString()!="")
				{
					model.total_amount=decimal.Parse(row["total_amount"].ToString());
				}
				if(row["received"]!=null && row["received"].ToString()!="")
				{
					model.received=decimal.Parse(row["received"].ToString());
				}
				if(row["not_received"]!=null && row["not_received"].ToString()!="")
				{
					model.not_received=decimal.Parse(row["not_received"].ToString());
				}
				if(row["state"]!=null && row["state"].ToString()!="")
				{
					model.state=int.Parse(row["state"].ToString());
				}
				if(row["create_time"]!=null && row["create_time"].ToString()!="")
				{
					model.create_time=DateTime.Parse(row["create_time"].ToString());
				}
			}
			return model;
		}

		/// <summary>
		/// 获得数据列表
		/// </summary>
		public DataSet GetList(string strWhere)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select id,settlement_num,user_name,total_amount,received,not_received,state,create_time ");
			strSql.Append(" FROM sf_finance_settlement ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			return DbHelperSQL.Query(strSql.ToString());
		}

		/// <summary>
		/// 获得前几行数据
		/// </summary>
		public DataSet GetList(int Top,string strWhere,string filedOrder)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select ");
			if(Top>0)
			{
				strSql.Append(" top "+Top.ToString());
			}
			strSql.Append(" id,settlement_num,user_name,total_amount,received,not_received,state,create_time ");
			strSql.Append(" FROM sf_finance_settlement ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			strSql.Append(" order by " + filedOrder);
			return DbHelperSQL.Query(strSql.ToString());
		}

		/// <summary>
		/// 获取记录总数
		/// </summary>
		public int GetRecordCount(string strWhere)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("select count(1) FROM sf_finance_settlement ");
			if(strWhere.Trim()!="")
			{
				strSql.Append(" where "+strWhere);
			}
			object obj = DbHelperSQL.GetSingle(strSql.ToString());
			if (obj == null)
			{
				return 0;
			}
			else
			{
				return Convert.ToInt32(obj);
			}
		}



        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public SF.Model.sf_finance_settlement GetModel(string settlement_num)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("select  top 1 id,settlement_num,user_name,total_amount,received,not_received,state,create_time from sf_finance_settlement ");
            strSql.Append(" where settlement_num=@settlement_num");
            SqlParameter[] parameters = {
					new SqlParameter("@settlement_num", SqlDbType.NVarChar,50)
			};
            parameters[0].Value = settlement_num;

            SF.Model.sf_finance_settlement model = new SF.Model.sf_finance_settlement();
            DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return DataRowToModel(ds.Tables[0].Rows[0]);
            }
            else
            {
                return null;
            }
        }

		/// <summary>
		/// 分页获取数据列表
		/// </summary>
		public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
		{
			StringBuilder strSql=new StringBuilder();
			strSql.Append("SELECT * FROM ( ");
			strSql.Append(" SELECT ROW_NUMBER() OVER (");
			if (!string.IsNullOrEmpty(orderby.Trim()))
			{
				strSql.Append("order by T." + orderby );
			}
			else
			{
				strSql.Append("order by T.id desc");
			}
			strSql.Append(")AS Row, T.*  from sf_finance_settlement T ");
			if (!string.IsNullOrEmpty(strWhere.Trim()))
			{
				strSql.Append(" WHERE " + strWhere);
			}
			strSql.Append(" ) TT");
			strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
			return DbHelperSQL.Query(strSql.ToString());
		}


        /// <summary>
        /// 获取最近一次的结算单
        /// </summary>
        /// <returns></returns>
        public Model.sf_finance_settlement GetLastModel()
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select  top 1 id,settlement_num,user_name,total_amount,received,not_received,state,create_time from sf_finance_settlement ");
            strSql.Append(" order by settlement_num desc");

            SF.Model.sf_finance_settlement model = new SF.Model.sf_finance_settlement();
            DataSet ds = DbHelperSQL.Query(strSql.ToString(), null);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return DataRowToModel(ds.Tables[0].Rows[0]);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        public DataSet GetList(int pageSize, int pageIndex, string strWhere, string filedOrder, out int recordCount)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * from sf_finance_settlement");
            if (!string.IsNullOrEmpty(strWhere.Trim()))
            {
                strSql.Append(" WHERE " + strWhere);
            }
            recordCount = Convert.ToInt32(DbHelperSQL.GetSingle(PagingHelper.CreateCountingSql(strSql.ToString())));
            return DbHelperSQL.Query(PagingHelper.CreatePagingSql(recordCount, pageSize, pageIndex, strSql.ToString(), filedOrder));
        }


        /// <summary>
        /// 保存财务结算结果
        /// </summary>
        /// <returns></returns>
        public bool SaveSettlementResult(System.Data.DataTable dtFinance, 
            System.Data.DataTable dtBusiness,
            System.Data.DataTable dtApp, System.Data.DataTable dtOrders)
        {
            using (SqlConnection conn = new SqlConnection(DbHelperSQL.connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {

                        #region dtFinance 

                        StringBuilder strSql0 = new StringBuilder();
                        strSql0.Append("insert into sf_finance_settlement(");
                        strSql0.Append("settlement_num,user_name,total_amount,received,not_received,state,create_time)");
                        strSql0.Append(" values (");
                        strSql0.Append("@settlement_num,@user_name,@total_amount,@received,@not_received,@state,@create_time)");
                        strSql0.Append(";select @@IDENTITY");
                        SqlParameter[] parameters0 = {
					        new SqlParameter("@settlement_num", SqlDbType.NVarChar,100),
					        new SqlParameter("@user_name", SqlDbType.NVarChar,100),
					        new SqlParameter("@total_amount", SqlDbType.Decimal,9),
					        new SqlParameter("@received", SqlDbType.Decimal,9),
					        new SqlParameter("@not_received", SqlDbType.Decimal,9),
					        new SqlParameter("@state", SqlDbType.Int,4),
					        new SqlParameter("@create_time", SqlDbType.DateTime)};

                        foreach (System.Data.DataRow r in dtFinance.Rows) 
                        {
                            parameters0[0].Value = r["settlement_num"].ToString();
                            parameters0[1].Value = r["user_name"].ToString();
                            parameters0[2].Value = decimal.Parse(r["total_amount"].ToString());
                            parameters0[3].Value = decimal.Parse(r["received"].ToString());
                            parameters0[4].Value = decimal.Parse(r["not_received"].ToString());
                            parameters0[5].Value = int.Parse(r["state"].ToString());
                            parameters0[6].Value = r["create_time"].ToString();

                            object obj = DbHelperSQL.GetSingle(conn, trans, strSql0.ToString(), parameters0); //带事务
                        }

                        #endregion

                        #region dtBusiness

                        StringBuilder strSql1 = new StringBuilder();
                        strSql1.Append("insert into sf_business_settlement(");
                        strSql1.Append("sf_finance_settlement_num,busnieseNum,businessName,sf_contract_num,settlement_times,user_name,total_amount,state,pay_num,pay_time,notice_count,create_time)");
                        strSql1.Append(" values (");
                        strSql1.Append("@sf_finance_settlement_num,@busnieseNum,@businessName,@sf_contract_num,@settlement_times,@user_name,@total_amount,@state,@pay_num,@pay_time,@notice_count,@create_time)");
                        strSql1.Append(";select @@IDENTITY");
                        SqlParameter[] parameters1 = {
					        new SqlParameter("@sf_finance_settlement_num", SqlDbType.NVarChar,100),
					        new SqlParameter("@busnieseNum", SqlDbType.NVarChar,50),
					        new SqlParameter("@businessName", SqlDbType.NVarChar,50),
					        new SqlParameter("@sf_contract_num", SqlDbType.NVarChar,50),
					        new SqlParameter("@settlement_times", SqlDbType.NVarChar,100),
					        new SqlParameter("@user_name", SqlDbType.NVarChar,100),
					        new SqlParameter("@total_amount", SqlDbType.Decimal,9),
					        new SqlParameter("@state", SqlDbType.Int,4),
					        new SqlParameter("@pay_num", SqlDbType.NVarChar,100),
					        new SqlParameter("@pay_time", SqlDbType.DateTime),
					        new SqlParameter("@notice_count", SqlDbType.Int,4),
					        new SqlParameter("@create_time", SqlDbType.DateTime)};

                        foreach (System.Data.DataRow r in dtBusiness.Rows) 
                        { 
                            parameters1[0].Value = r["sf_finance_settlement_num"].ToString();
                            parameters1[1].Value = r["busnieseNum"].ToString(); 
                            parameters1[2].Value = r["businessName"].ToString(); 
                            parameters1[3].Value = r["sf_contract_num"].ToString(); 
                            parameters1[4].Value = r["settlement_times"].ToString();
                            parameters1[5].Value = r["user_name"].ToString();
                            parameters1[6].Value = decimal.Parse(r["total_amount"].ToString());
                            parameters1[7].Value = int.Parse(r["state"].ToString());
                            parameters1[8].Value = r["pay_num"].ToString();
                            parameters1[9].Value = null;
                            parameters1[10].Value = int.Parse(r["notice_count"].ToString());
                            parameters1[11].Value = DateTime.Parse(r["create_time"].ToString());

                            object obj = DbHelperSQL.GetSingle(conn, trans, strSql1.ToString(), parameters1); //带事务
                        }

                        #endregion

                        #region dtApp

                        StringBuilder strSql2 = new StringBuilder();
                        strSql2.Append("insert into sf_businessapp_settlement(");
                        strSql2.Append("sf_finance_settlement_num,busnieseNum,business_name,appNum,appid_name,templatesNum,templates_name,sf_contract_num,settlement_times,user_name,total_amount,create_time)");
                        strSql2.Append(" values (");
                        strSql2.Append("@sf_finance_settlement_num,@busnieseNum,@business_name,@appNum,@appid_name,@templatesNum,@templates_name,@sf_contract_num,@settlement_times,@user_name,@total_amount,@create_time)");
                        strSql2.Append(";select @@IDENTITY");
                        SqlParameter[] parameters2 = {
					        new SqlParameter("@sf_finance_settlement_num", SqlDbType.NVarChar,100),
					        new SqlParameter("@busnieseNum", SqlDbType.NVarChar,50),
					        new SqlParameter("@business_name", SqlDbType.NVarChar,100),
					        new SqlParameter("@appNum", SqlDbType.NVarChar,50),
					        new SqlParameter("@appid_name", SqlDbType.NVarChar,100),
					        new SqlParameter("@templatesNum", SqlDbType.NVarChar,100),
					        new SqlParameter("@templates_name", SqlDbType.NVarChar,100),
					        new SqlParameter("@sf_contract_num", SqlDbType.NVarChar,50),
					        new SqlParameter("@settlement_times", SqlDbType.NVarChar,100),
					        new SqlParameter("@user_name", SqlDbType.NVarChar,100),
					        new SqlParameter("@total_amount", SqlDbType.Decimal,9),
					        new SqlParameter("@create_time", SqlDbType.DateTime)};
                        

                        foreach (System.Data.DataRow r in dtApp.Rows)
                        {
                            parameters2[0].Value = r["sf_finance_settlement_num"].ToString(); 
                            parameters2[1].Value = r["busnieseNum"].ToString();
                            parameters2[2].Value = r["business_name"].ToString();
                            parameters2[3].Value = r["appNum"].ToString();
                            parameters2[4].Value = r["appid_name"].ToString();
                            parameters2[5].Value = r["templatesNum"].ToString();
                            parameters2[6].Value = r["templates_name"].ToString();
                            parameters2[7].Value = r["sf_contract_num"].ToString();
                            parameters2[8].Value = r["settlement_times"].ToString();
                            parameters2[9].Value = r["user_name"].ToString();
                            parameters2[10].Value = decimal.Parse(r["total_amount"].ToString());
                            parameters2[11].Value = DateTime.Parse(r["create_time"].ToString());

                            object obj = DbHelperSQL.GetSingle(conn, trans, strSql2.ToString(), parameters2); //带事务
                        }

                        #endregion

                        #region dtOrders

                        StringBuilder strSql3 = new StringBuilder();
                        strSql3.Append("insert into sf_ordersettlement(");
                        strSql3.Append("sf_finance_settlement_num,busnieseNum,appNum,templatesNum,order_num,payMoney,amount,settlement_time)");
                        strSql3.Append(" values (");
                        strSql3.Append("@sf_finance_settlement_num,@busnieseNum,@appNum,@templatesNum,@order_num,@payMoney,@amount,@settlement_time)");
                        strSql3.Append(";select @@IDENTITY");
                        SqlParameter[] parameters3 = {
					        new SqlParameter("@sf_finance_settlement_num", SqlDbType.NVarChar,100),
                            new SqlParameter("@busnieseNum", SqlDbType.NVarChar,100),
                            new SqlParameter("@appNum", SqlDbType.NVarChar,100),
                            new SqlParameter("@templatesNum", SqlDbType.NVarChar,100),
					        new SqlParameter("@order_num", SqlDbType.NVarChar,100),
                            new SqlParameter("@payMoney", SqlDbType.Decimal,9),
					        new SqlParameter("@amount", SqlDbType.Decimal,9),
					        new SqlParameter("@settlement_time", SqlDbType.DateTime)};

                        foreach (System.Data.DataRow r in dtOrders.Rows)
                        {
                            parameters3[0].Value = r["sf_finance_settlement_num"].ToString();
                            parameters3[1].Value = r["busnieseNum"].ToString();
                            parameters3[2].Value = r["appNum"].ToString();
                            parameters3[3].Value = r["templatesNum"].ToString();
                            parameters3[4].Value = r["order_num"].ToString();
                            parameters3[5].Value = r["payMoney"].ToString();
                            parameters3[6].Value = decimal.Parse(r["amount"].ToString());
                            parameters3[7].Value = DateTime.Parse(r["settlement_time"].ToString());

                            object obj = DbHelperSQL.GetSingle(conn, trans, strSql3.ToString(), parameters3); //带事务

                            //修改订单表结算状态
                            string temp_sql = "update sf_goods_order set isComDone = 1 , comDoneTime =  '" + DateTime.Parse(r["settlement_time"].ToString()) +"' where ordernum = '" + r["order_num"].ToString() + "'";
                            DbHelperSQL.ExecuteSql(conn, trans, temp_sql);
                        }

                        #endregion



                        //如无异常则提交事务
                        trans.Commit();
                    }
                    catch
                    {
                        trans.Rollback();
                        return false;
                    }
                }
            }

            return true;
        }

		/*
		/// <summary>
		/// 分页获取数据列表
		/// </summary>
		public DataSet GetList(int PageSize,int PageIndex,string strWhere)
		{
			SqlParameter[] parameters = {
					new SqlParameter("@tblName", SqlDbType.VarChar, 255),
					new SqlParameter("@fldName", SqlDbType.VarChar, 255),
					new SqlParameter("@PageSize", SqlDbType.Int),
					new SqlParameter("@PageIndex", SqlDbType.Int),
					new SqlParameter("@IsReCount", SqlDbType.Bit),
					new SqlParameter("@OrderType", SqlDbType.Bit),
					new SqlParameter("@strWhere", SqlDbType.VarChar,1000),
					};
			parameters[0].Value = "sf_finance_settlement";
			parameters[1].Value = "id";
			parameters[2].Value = PageSize;
			parameters[3].Value = PageIndex;
			parameters[4].Value = 0;
			parameters[5].Value = 0;
			parameters[6].Value = strWhere;	
			return DbHelperSQL.RunProcedure("UP_GetRecordByPage",parameters,"ds");
		}*/

		#endregion  BasicMethod
		#region  ExtensionMethod

		#endregion  ExtensionMethod
	}
}

